"use strict";

var debugLog = require('../../function.js').debugLog;

function Pool() {
    // 请求管理
    this.maxConnSize = 1000; // 最大请求数
    this.connSize = 1; // 正在处理的请求数
    this.maxPoolSize = 1000;
    this.pool = [];
}
module.exports = Pool;
var theProto = Pool.prototype;

/**
 * 在请求到es服务器之前,检测正在处理的请求数
 * @returns {*}
 */
theProto.preRequestHandle = function*() {
    var self = this;
    debugLog('connSize=' + self.connSize, 'poolSize=' + self.pool.length);
    if (self.connSize < self.maxConnSize) {
        self.connSize++;
        return {error: null, result: true}
    }

    if (self.pool.length < self.maxPoolSize) { // 放到队列中,不返回
        debugLog('--------------now wait');
        return new Promise(function (fulfill, r) {
            self.pool.push(fulfill);
        }).then(function (res) {
                debugLog('fulfil now:', res);
                return res;
            });
    } else { // 直接拒绝
        return {error: 'server reach max capability'}
    }
};

/**
 * 将正在处理的请求数目 -1,并激活 池中等待的下一个
 * @returns {string}
 */
theProto.postRequestHandle = function* () {
    debugLog('postRequestHandle');
    var self = this;
    self.connSize--;
    if (this.pool.length > 0) {
        debugLog('get from list ..........');
        self.connSize++;
        var fulfill = this.pool.shift();
        fulfill({error: null, result: true});
    }
    return 'ok';
};